import os

import auth


def updateTokenInfo(api_response, token_file_path):
    import json
    strResp = repr(api_response).replace("'","\"")
    jsonObj = json.loads(strResp)
    with open(token_file_path, 'w+') as file:
        json.dump(jsonObj, file)
        logger.info("保存refresh信息至文件")


def readTokenInfo(token_file_path):
    import json
    with open(token_file_path, 'r') as file:
        response = json.load(file)
        return response


def dumpSql(nowtime, store_dir_path):
    logger.info("进行数据库备份")
    sql_path = store_dir_path + "/halodb_" + nowtime + ".sql"
    if os.path.exists(sql_path):
        logger.info("存在历史数据 "+sql_path+"，进行重命名")
        os.rename(sql_path,sql_path+"_bak")
    bash_shell = "mysqldump -h116.*.*.63 -P3306 -uroot -p'!' halodb  --max_allowed_packet=512M --set-gtid-purged=OFF > " + sql_path
    result = os.popen(bash_shell)
    logger.info("执行命令的结果为：" + result.read())

def dumpHalo(nowtime, store_dir_path):
    logger.info("进行 博客数据备份")
    halo_path = store_dir_path + "/halodb_" + nowtime + ".tar.gz"
    if os.path.exists(halo_path):
        logger.info("存在历史数据 "+halo_path+"，进行重命名")
        os.rename(halo_path,halo_path+"_bak")
    bash_shell = " tar -zcf "+halo_path+" --exclude=/root/.halo/logs /root/.halo"
    result = os.popen(bash_shell)
    logger.info(bash_shell+ " 执行命令的结果为：" + result.read())

def tarDumpResult(store_dir_path):
    tarName = store_dir_path+".tar.gz"
    bash_shell = " tar -zcf "+tarName+" --exclude=*_bak "+store_dir_path
    if os.path.exists(tarName):
        logger.info("存在历史数据 "+tarName+"，进行重命名")
        os.rename(tarName,tarName+"_bak")
    logger.info("开始打包整体数据，命令为："+bash_shell)
    result = os.popen(bash_shell)
    logger.info("执行命令的结果为：" + result.read())


if __name__ == '__main__':
    import logging

    import time
    import upload
    import socket
    socket.setdefaulttimeout(300)

    nowtime = time.strftime("%Y%m%d", time.localtime())

    logging.basicConfig(level=logging.INFO,filename="../logs/log"+nowtime+".log", format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    logger = logging.getLogger(__name__)

    token_file_path = "../token_info.json"
    #TODO 应用信息
    client_id = ""  # str |
    client_secret = ""  # str |

    response = readTokenInfo(token_file_path)
    access_token = response["access_token"]
    refresh_token = response["refresh_token"]
    expires_in = response["expires_in"]
    if expires_in < 7 * 24 * 60:
        logger.info("token有效期不足7天，故更新token")

        api_response = auth.oauthtoken_refreshtoken(refresh_token, client_id, client_secret)
        updateTokenInfo(api_response, token_file_path)
        access_token = api_response["access_token"]


    store_dir_path = "/root/mysqlbackup/" + nowtime
    if not os.path.exists(store_dir_path):
        os.makedirs(store_dir_path)
    logger.info("开始进行博客 halo 备份")
    dumpSql(nowtime, store_dir_path)
    dumpHalo(nowtime,store_dir_path)
    tarDumpResult(store_dir_path)
    upload.mkdir(nowtime,access_token,logger=logger)
    upload.uploadFile(filePath=store_dir_path+".tar.gz",fileName=nowtime+"/"+nowtime+".tar.gz",access_token=access_token,logger=logger)




